package com.syy.mapjoin;

import com.syy.reducejoin.OrderJoin;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class MapJoinMapper extends Mapper<LongWritable, Text, OrderJoin, NullWritable>{
    private Map<String, String> map = new HashMap<>();
    private OrderJoin orderJoin = new OrderJoin();

    @Override
    protected void setup(Mapper<LongWritable, Text, OrderJoin, NullWritable>.Context context) throws IOException, InterruptedException {
        FileSystem fileSystem = FileSystem.get(context.getConfiguration());
        FSDataInputStream open = fileSystem.open(new Path("F:\\projects\\JavaProjects\\myproject\\JavaProjects\\MapReduceDemo\\src\\main\\resources\\input3\\product.txt"));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(open, "UTF-8"));
        String line;
        while(StringUtils.isNotEmpty(line = bufferedReader.readLine())) {
            String[] lines = line.split("\t");
            System.out.println(lines[0] + "----" + lines[1]);
            map.put(lines[0], lines[1]);
        }
        IOUtils.closeStream(bufferedReader);
    }

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, OrderJoin, NullWritable>.Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] lines = line.split("\t");
        orderJoin.setOid(lines[0]);
        orderJoin.setPid(lines[1]);
        orderJoin.setCount(Integer.parseInt(lines[2]));


        orderJoin.setpName(map.get(lines[1]));
        context.write(orderJoin, NullWritable.get());
    }
}
